<?
class FormBuilder {
	public static function build($obj, $edit_vars, $url = '', $back_url = 'back', $errors = '', $delete_url = null){
		if($back_url == "back"){
			$back_url = $_SERVER['HTTP_REFERER'];
		}else {
			$back_url = getBaseUrl().$back_url;
		}

        if($obj->getId() != null && $obj->getId() > 0){
            $html = '<h2>'.translate("Editing_".get_class($obj)).'</h2>';
        } else {
            $html = '<h2>'.translate("Creating_".get_class($obj)).'</h2>';
        }

        $html .= '<form method="post" action="'.getBaseUrl().$url.'" name="form'.get_class($obj).'" enctype="multipart/form-data">';

        $html .= '<div class="mainpanel">';
		foreach($edit_vars as $key => $value){
			$disable = "";
			$getkeyid = $key."_id";

			$type = $value["type"];
			$enabled = true;
			
			$fieldname = str_replace('.', '_', $key);
			
			$label_key = $key;
			$help = "";
			
			$reflectionValue = ReflectionUtils::getFieldValue($obj, $key);

			if(isset($value["disabled"])){
				$enabled = false;
			}
			if(isset($value["label"])){
				$label_key = $value["label"];
			}

			if(isset($value["help"])){
				$help = '<label for="'.$key.'" class="help">['.translate($value["help"]).']</label>';
			}

			if(!$enabled && isset($obj->id)){ $disable = "disabled"; }
 
			if($type != "HIDDEN" && $type != "SEPARATOR"){
				$html .= '<fieldset>';
				$html .= '<label for="'.$fieldname.'">'.translate($label_key).'</label>';
			}

		
			if($type == "HIDDEN"){
				$html .= '<input type="hidden" value="'.$reflectionValue.'" name="'.$fieldname.'" id="'.$fieldname.'"/>';
			} else if($type == "TEXT" || $type == "NUMERIC"){
				$html .= '<input type="text" value="'.$reflectionValue.'" name="'.$fieldname.'" id="'.$fieldname.'"'.$disable.' class="field"/>'.$help.'<br/>';
			} else if($type == "BIGTEXT"){
				$html .= '<textarea name="'.$fieldname.'" id="'.$fieldname.'" '.$disable.' class="textarea">'.$reflectionValue.'</textarea>'.$help.'<br/>';
			} else if($type== "EMAIL"){
				$html .= '<input type="text" value="'.$reflectionValue.'" class="field" name="'.$fieldname.'" id="'.$fieldname.'" '.$disable.'/>'.$help.'<br/>';
			} else if($type == "BOOLEAN"){
				$html .= '<input name="'.$fieldname.'" type="checkbox" value="checkbox" '.($reflectionValue == true ? 'checked="checked"' : '').' class="checkbox"/><br/>';
			} else if($type == "PASSWORD"){
				$html .= '<input type="password" value="'.$reflectionValue.'" class="field" name="'.$fieldname.'" id="'.$fieldname.'" '.$disable.'/>';
			} else if($type == "DATE"){
				$html .= '<input type="text" value="'.$reflectionValue.'" class="field, datepicker" name="'.$fieldname.'" id="'.$fieldname.'" '.$disable.'/>';
				if($value["showTime"]){
					$html .= "<a href=javascript:NewCssCal('$key','yyyymmdd','dropdown',true)>";
				} else {
					$html .= "<a href=javascript:NewCssCal('$key','yyyymmdd')>";
				}
				
				$html .= '<img  align="absmiddle" src="'.getTemplateUrl().'images/calbtn.gif" width="34" height="22" border="0" alt=""></a>';
				$html .= $help.'<br/>';
			} else if($type == "VEDITOR"){
				$html .= '<textarea name="'.$fieldname.'" id="'.$fieldname.'" '.$disable.' class="mceEditor"/>'.$reflectionValue.'</textarea>'.$help.'<br/>';
			} else if($type == "OBJECT"){
				$html .= '<select name="'.$fieldname.'" id="'.$fieldname.'" class="select" '.$disable.'>';
				if($value["emptyselection"] == "TRUE"){
					$html .= '<option value="-1">'.translate("nothing_selected").'</option>';
				}
				$objList = db::get($value["target"]);
				$selected = ReflectionUtils::getValue($obj, $key."_id");
				
				for($i = 0; $i < count($objList); $i++){
					$html .= '<option value="'.$objList[$i]->getId().'" '.(($objList[$i]->getId() == $selected) ? "selected" : "").'>'.$objList[$i]->toString().'</option>';
				}
				$html .= '</select>'.$help.'<br/>';
			} else if($type == "IMAGE"){ 
			} else if($type == "FILE"){
				$fileid = "null";
				if($reflectionValue != null){
					$html .= $reflectionValue->getPreview()."<br/>";
					$fileid = $reflectionValue->getId();
				}
				$html .= '<input type="hidden" value="'.$fileid.'" name="'.$fieldname.'" id="'.$fieldname.'"/>';
				$html .= '<label></label><input type="file" name="'.$fieldname.'_file" id="'.$fieldname.'_file"/>'.$help.'<br/>';
			} else if($type == "SEPARATOR"){
				$html .= '<hr/>';
				if(isset($value["titel"])){
					$html .= '<h3>'.$value["titel"].'</h3>';
				}
			} else if($type == "AUTOCOMPLETE"){
                $html .= FormBuilder::createAutocomplete($fieldname, $value["indicator"], $value["controller"], $value["action"], $value["afterUpdateElement"]);
            }

			if($type != "HIDDEN" && $type != "SEPARATOR"){
				$html .= '</fieldset>';
			}
			
			if(isset($errors[$key])){
				$html .= '<fieldset><label class="error">'.$errors[$key].'</label></fieldset>';
			}
			
			if($type == "PASSWORD"){
				$html .= '<fieldset><label>'.translate('verification').'</label>';
				$html .= '<input type="password" value="'.$reflectionValue.'" class="field" name="'.$fieldname.'_" '.$disable.'/>'.$help.'<br/>';
				$html .= '</fieldset>';
			}
			
			$html .= "\n";
		}

		$html .= '<fieldset>';

        $html .= '</div>';
		
		if(isset($back_url)){
			$html .= '<input type="button" onclick="window.location=\''.$back_url.'\'" value="'.translate("back").'" class="button"/>';
		}

		if(isset($delete_url)){
			$html .= '<input type="button" onclick="if(confirmDialog(\''.translate("Are_you_sure_you_want_to_delete?").'\')){window.location=\''.getBaseUrl().$delete_url.'\'}" value="'.translate("delete").'" class="button"/>';
		}
		$html .= '<input type="submit" value="'.translate("save").'" class="button"/>';
		$html .= '</fieldset>';
		$html .= '</form>';
		return $html;
	}

    private static function createAutocomplete($fieldname, $indicator, $controller, $action, $afterUpdateElement){
        $html = '';
        $html .= '<input type="text" id="'.$fieldname.'" class="field" name="'.$fieldname.'" autocomplete="off"/>';
        $html .= '<div id="'.$fieldname.'_choices" class="autocomplete"></div>';

        $indicatorHTML = "";
        $afterUpdateHTML = "";
        $paramsHTML = "";

        if(isset($indicator)){
            $html .= '<span id="'.$fieldname.'_indicator" style="display:none" class="indicator"><img src="'.resourceUrl($indicator).'" alt="Loading..." /></span>';
            $paramsHTML = " indicator: '".$fieldname."_indicator' ";
        }

        if(isset($afterUpdateElement)){
            if(isset($indicator)){
                $paramsHTML .= ", ";
            }
            $paramsHTML .= "afterUpdateElement: ".$afterUpdateElement;
        }

        $html .= '<script type="text/javascript">new Ajax.Autocompleter(\''.$fieldname.'\',\''.$fieldname.'_choices\',\''.url($controller, $action).'\', {'.$paramsHTML.'});</script>';
        return $html;

    }
	
	private static function formValue($key){
		$formname = str_replace('.', '_', $key);
		return $_POST[$formname];
	}
	
	private static function isFormValueAvailable($key){
		$formname = str_replace('.', '_', $key);
		return isset($_POST[$formname]);
	}
	
	public static function validate($obj, $edit_vars){
		$errors = Array();
		$methods = get_class_methods($obj);
		$hashtable = Array();
		for($i = 0; $i < count($methods); $i++){
			$hashtable[strtolower($methods[$i])] = true;
		}

		foreach($edit_vars as $key => $value){
			$type = $value["type"];
			$enabled = true;
			if(isset($value["disabled"])){
				$enabled = false;
			}

			if( ((isset($obj->id) && $enabled) || !isset($obj->id)) && $key != "id"){
				if($type == "OBJECT" || $type == "IMAGE"){
					$keyid = $key."_id";
					ReflectionUtils::setValue($obj, $keyid, FormBuilder::formValue($key));
 				} else if($type == "VEDITOR" || $type == "TEXT" || $type == "BIGTEXT"){
					$text = FormBuilder::formValue($key);
					$text = str_replace("\n", "", $text);
					$text = str_replace("\\", "", $text);
					$text = str_replace("\r", "", $text);
					$text = str_replace("'", "\'", $text);
					
					ReflectionUtils::setFieldValue($obj, $key, $text);
				} else if($type == "BOOLEAN"){
					if(FormBuilder::isFormValueAvailable($key)){
						ReflectionUtils::setFieldValue($obj, $key, true);
					} else {
						ReflectionUtils::setFieldValue($obj, $key, false);
					}
				} else if($type == "DATE"){
	  				ReflectionUtils::setFieldValue($obj, $key, FormBuilder::formValue($key));
				} else if($type == "FILE"){
					$folderid = 2; // By default go to temp folder
					$valid = true;
					$folder = db::get(Folder, $folderid);

					$filekey = $key."_file";
					$filename = $_FILES[$filekey]['name'];

					$validfile = true;

					if(isset($value["extension"])){
						if(File::isExtension($filename, explode(",", strtolower($value["extension"])))){
							$validfile = true;
						} else {
							$validfile = false;
						}
					}

					$oldimg = db::get(Image, FormBuilder::formValue($key));

					if(isset($_FILES[$filekey]['name']) && $_FILES[$filekey]['name'] != ""){
						if($validfile){
							$file = new File();
							if(Image::isImage($filename)){
								$file = new Image();
							}
							$file->setFolder($folder);
							if($file->upload($_FILES[$filekey]['name'], $_FILES[$filekey]['tmp_name'])) {
								if($oldimg != null){
									db::delete($oldimg);
								}
								ReflectionUtils::setFieldValue($obj, $key, $file);
							}
						} else {
							$errors[$key] = translate("extension_should_be_of_type").":".strtolower($value["extension"]);
						}
					}else {
						ReflectionUtils::setFieldValue($obj, $key, $oldimg);
					}
				}

				$method = "validate".$key;
				
				if($type == "PASSWORD"){
					if(FormBuilder::formValue($key) != FormBuilder::formValue($key."_")){
						$errors[$key] = translate("password_doesnt_match");
					}
					ReflectionUtils::setFieldValue($obj, $key, FormBuilder::formValue($key));
				}
				if($hashtable[strtolower($method)]){
					$error = $obj->$method();
					if(isset($error)){
						$errors[$key] = $error;
					}
				}
			}
		}
		// If there are no errors, so move uploaded files to target folder
		if(count($errors) == 0){
			foreach($edit_vars as $key => $value){
				$getkey = 'get'.$key;
				if($value["type"] == "FILE"){
					$folderid = $value["default_folder"];
					$folder = db::get(Folder, $folderid);

					$img = $obj->$getkey();
					if($img != null){
						$img->setFolder($folder);
						db::save($img);
					}
				}
			}
			if(isset($value["default_folder"])){
				$folderid = $value["default_folder"];
			}
		}
		return $errors;
	}
}
?>